import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Role } from './entities/role.entity';
import { Menu } from '../menus/entities/menu.entity';
import { CreateRoleDto } from './dto/create-role.dto';
import { UpdateRoleDto } from './dto/update-role.dto';

@Injectable()
export class RolesService {
  constructor(
    @InjectRepository(Role)
    private rolesRepository: Repository<Role>,
    @InjectRepository(Menu)
    private menusRepository: Repository<Menu>,
  ) {}

  async create(createRoleDto: CreateRoleDto) {
    const { menuIds, ...roleData } = createRoleDto;
    const role = this.rolesRepository.create(roleData);

    if (menuIds?.length) {
      const menus = await this.menusRepository.findByIds(menuIds);
      role.menus = menus;
    }

    return this.rolesRepository.save(role);
  }

  findAll() {
    return this.rolesRepository.find({
      relations: ['menus'],
    });
  }

  async findOne(id: number) {
    const role = await this.rolesRepository.findOne({
      where: { id },
      relations: ['menus'],
    });

    if (!role) {
      throw new NotFoundException(`Role with ID ${id} not found`);
    }

    return role;
  }

  async update(id: number, updateRoleDto: UpdateRoleDto) {
    const { menuIds, ...roleData } = updateRoleDto;
    const role = await this.findOne(id);

    if (menuIds) {
      const menus = await this.menusRepository.findByIds(menuIds);
      role.menus = menus;
    }

    Object.assign(role, roleData);
    return this.rolesRepository.save(role);
  }

  async remove(id: number) {
    const role = await this.findOne(id);
    return this.rolesRepository.remove(role);
  }
} 